package com.qf.qfgateway.filters;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.qf.pojo.R;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Order(-5)
@Component
public class LoginFilter implements GlobalFilter/*, Ordered*/ {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest req = exchange.getRequest();
        ServerHttpResponse resp = exchange.getResponse();

        //放行一些不需要拦截的资源
        String path = req.getURI().getPath();
        if (path.endsWith("/login")){
            //放行
            return chain.filter(exchange);
        }

        //拦截需要处理的资源(登录认证) -- token
        //获取请求头中的token信息
        String token = req.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)){
            //获取请求路径中的token信息
            token = req.getQueryParams().getFirst("token");

            if (StringUtils.isBlank(token)){
                //没有携带认证token --> 提示用户去登录
//                resp.setStatusCode(HttpStatus.UNAUTHORIZED);
//                return resp.setComplete();

                //解决响应中文乱码问题
                resp.getHeaders().set("content-type","application/json;charset=utf-8");

                //向页面响应统一的R对象数据
                R r = R.error().putMsg("还未登录，请先登录！");
                String json = JSON.toJSONString(r);

                //将数据通过数据缓冲工厂对象处理
                DataBuffer dataBuffer = resp.bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));
                //根据这个数据缓冲对象获取一个Mono对象
                Mono<DataBuffer> bufferMono = Mono.just(dataBuffer);
                //将这个包含数据的Mono对象响应到页面
                return resp.writeWith(bufferMono);
            }
        }

        //对token进行jwt的校验

        //校验通过，放行到目标资源
        return chain.filter(exchange);
    }

   /* @Override
    public int getOrder() {
        return 0;
    }*/
}
